package com.ruoyi.framework.interceptor;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.RedisService;
import com.ruoyi.common.utils.StrKit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Writer;
import java.util.Enumeration;

/**
 * 供应商拦截器
 */
@Component
public class BalanceInterceptoer implements HandlerInterceptor {

    @Autowired
    RedisService redis;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        boolean ifPass = false;
        boolean ifmac = false;

        String url=request.getRequestURI();
        String token=request.getHeader("token");
        String mac=request.getHeader("mac");

        System.out.println("url : "+url);
        System.out.println("head信息");
        //打印所有head入参
        Enumeration<String> headerNames=request.getHeaderNames();
        while(headerNames.hasMoreElements()){
            String headerName=headerNames.nextElement();
            String headerValue=request.getHeader(headerName);
            System.out.println(headerName+":"+headerValue);
        }

        if(StrKit.notBlank(mac)){
            ifmac=true;
        }
        System.out.println("ifmac:"+ifmac);
        if(url.endsWith("/balance/login")//登录
        )//不经过过滤器的路径
        {
            System.out.println("通过过滤器");
            ifPass=true;
            ifmac=true;
        }else{
//			System.out.println("chekcKey:"+chekcKey);
            if(StrKit.notBlank(token))
            {
                //测试token
                if(token.equals(Constants.testToken))ifPass= true;
                if(redis.getVal(Constants.SUPPLY_APP_TOKEN_KEY+token)!=null)ifPass= true;
            }
        }

        if(!ifPass){

            Writer writer=response.getWriter();

            AjaxResult ret=new AjaxResult();
            ret.put("code",-1);
            ret.put("msg","请先登录");
            writer.write(new JSONObject(ret).toString());
            writer.close();

            return false;
        }
        if(!ifmac){
            Writer writer=response.getWriter();

            AjaxResult ret=new AjaxResult();
            ret.put("code",-2);
            ret.put("msg","缺少关键信息");
            writer.write(new JSONObject(ret).toString());
            writer.close();
            return false;
        }

        //处理注解
        if(handler instanceof HandlerMethod){


        }

        return ifPass;
    }

}
